package com.mogist.hqc.oss;

import android.graphics.Bitmap;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import talex.zsw.basecore.util.BitmapTool;
import talex.zsw.basecore.util.Tool;

/**
 * 作用：阿里OSS图片提交
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
public class OssManager
{
	private OSS mOSS;
	private static volatile OssManager ossManager;

	private OssManager()
	{
	}

	public static OssManager getInstance()
	{
		if(ossManager == null)
		{
			synchronized(OssManager.class)
			{
				if(ossManager == null)
				{
					ossManager = new OssManager();
				}
			}
		}
		return ossManager;
	}

	/**
	 * 初始化OSS对象
	 */
	private OSS init()
	{
		if(mOSS == null)
		{
			OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider();
			ClientConfiguration conf = new ClientConfiguration();
			conf.setConnectionTimeout(15*1000); // 连接超时，默认15秒
			conf.setSocketTimeout(15*1000); // socket超时，默认15秒
			conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
			conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
			mOSS = new OSSClient(Tool.getContext(), OSSConfig.OSS_EndPoint, provider, conf);
		}
		return mOSS;
	}

	/**
	 * 图片上传
	 *
	 * @param bitmap           图片
	 * @param onUploadListener 回调监听
	 */
	public void upload(final int position, final Bitmap bitmap, final OnUploadListener onUploadListener)
	{
		Observable.just(init()).map(new Function<OSS, String>()
		{
			@Override public String apply(OSS oss) throws Exception
			{
				String picName = getUUIDByRules32Image();
				BitmapTool.compressByQuality(bitmap, 400*1024);
				File imageFile = BitmapTool.saveBitmap2File(bitmap, picName);
				// 创建上传的对象
				PutObjectRequest put = new PutObjectRequest(OSSConfig.OSS_BucketName,
				                                            OSSConfig.OSS_Dir+
					                                            picName, imageFile.getAbsolutePath());
				// 上传的进度回调
				put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>()
				{
					@Override
					public void onProgress(PutObjectRequest request, long currentSize, long totalSize)
					{
						if(onUploadListener != null)
						{
							onUploadListener.onProgress(position, currentSize, totalSize);
						}
					}
				});
				oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>()
				{
					@Override
					public void onSuccess(PutObjectRequest request, PutObjectResult result)
					{
						if(onUploadListener != null)
						{
							String imageUrl = request.getObjectKey();
							onUploadListener.onSuccess(position, OSSConfig.OSS_Prefix+"/"+imageUrl);
						}
					}

					@Override
					public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException)
					{
						if(serviceException != null)
						{
							serviceException.printStackTrace();
						}
						if(clientException != null)
						{
							clientException.printStackTrace();
						}
						if(onUploadListener != null)
						{
							onUploadListener.onFailure(position);
						}
					}
				});
				return imageFile.getAbsolutePath();
			}
		}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe();
	}

	public interface OnUploadListener
	{
		/**
		 * 上传的进度
		 */
		void onProgress(int position, long currentSize, long totalSize);

		/**
		 * 成功上传
		 */
		void onSuccess(int position, String imageUrl);

		/**
		 * 上传失败
		 */
		void onFailure(int position);
	}

	/**
	 * 上传到后台的图片的名称
	 */
	public static String getUUIDByRules32Image()
	{
		StringBuffer generateRandStr = null;
		try
		{
			String rules = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			int rpoint = 0;
			generateRandStr = new StringBuffer();
			Random rand = new Random();
			int length = 32;
			for(int i = 0; i < length; i++)
			{
				if(rules != null)
				{
					rpoint = rules.length();
					int randNum = rand.nextInt(rpoint);
					generateRandStr.append(rules.substring(randNum, randNum+1));
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		if(generateRandStr == null)
		{
			return "getUUIDByRules32Image.png";
		}
		return generateRandStr+".png";
	}
}
